import { useAuthStore } from '@/stores/auth-store'

// 定义角色类型
export type Role = 'admin' | 'user' | 'manager' | 'guest'

// 定义权限类型
export type Permission = 
  | 'read:users' 
  | 'write:users' 
  | 'delete:users'
  | 'read:dashboard'
  | 'write:dashboard'
  | 'read:settings'
  | 'write:settings'

// 角色权限映射
const rolePermissions: Record<Role, Permission[]> = {
  admin: [
    'read:users',
    'write:users',
    'delete:users',
    'read:dashboard',
    'write:dashboard',
    'read:settings',
    'write:settings'
  ],
  manager: [
    'read:users',
    'write:users',
    'read:dashboard',
    'write:dashboard',
    'read:settings'
  ],
  user: [
    'read:dashboard'
  ],
  guest: []
}

/**
 * 检查用户是否有指定角色
 */
export const useHasRole = (roles: Role | Role[]) => {
  const { auth } = useAuthStore()
  const userRoles = auth.user?.role || []
  
  const rolesArray = Array.isArray(roles) ? roles : [roles]
  return rolesArray.some(role => userRoles.includes(role))
}

/**
 * 检查用户是否有指定权限
 */
export const useHasPermission = (permissions: Permission | Permission[]) => {
  const { auth } = useAuthStore()
  const userRoles = auth.user?.role || []
  
  // 如果用户没有角色，则没有权限
  if (userRoles.length === 0) return false
  
  // 获取用户所有角色的权限
  const userPermissions = new Set<Permission>()
  userRoles.forEach(role => {
    const perms = rolePermissions[role as Role] || []
    perms.forEach(perm => userPermissions.add(perm))
  })
  
  // 检查是否拥有指定权限
  const permissionsArray = Array.isArray(permissions) ? permissions : [permissions]
  return permissionsArray.some(permission => userPermissions.has(permission))
}

/**
 * 权限检查Hook
 */
export const usePermissions = () => {
  const { auth } = useAuthStore()
  const userRoles = auth.user?.role || []
  
  // 获取用户所有权限
  const getUserPermissions = (): Permission[] => {
    const permissions = new Set<Permission>()
    userRoles.forEach(role => {
      const perms = rolePermissions[role as Role] || []
      perms.forEach(perm => permissions.add(perm))
    })
    return Array.from(permissions)
  }
  
  return {
    roles: userRoles,
    permissions: getUserPermissions(),
    hasRole: useHasRole,
    hasPermission: useHasPermission
  }
}